package com.ly.leave.service.impl;

import java.util.*;

import java.util.stream.Collectors;


import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.leave.domain.WorkflowLeave;
import com.ly.leave.mapper.WorkflowLeaveMapper;
import com.ly.leave.service.IWorkflowLeaveService;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 请假Service业务层处理
 * @author danny
 * @date 2020-10-28
 */
@Service
public class WorkflowLeaveServiceImpl implements IWorkflowLeaveService {

    @Resource
    private WorkflowLeaveMapper workflowLeaveMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private RepositoryService repositoryService;

    /**
     * 测试部署bpmnModel
     */
    public void deployBpmnModel(BpmnModel bpmnModel,String modelId){
        //部署流程模型
        Deployment deployment = repositoryService.createDeployment().name("deploymentName").addBpmnModel("process.bpmn", bpmnModel).deploy();
        //运行时service
//        runtimeService.startProcessInstanceById();
    }


    /**
     * 查询请假
     * @param id 请假ID
     * @return 请假
     */
    @Override
    public WorkflowLeave selectWorkflowLeaveById (String id) {
        return workflowLeaveMapper.selectWorkflowLeaveById ( id );
    }

    /**
     * 查询请假列表
     * @param workflowLeave 请假
     * @return 请假
     */
    @Override
    public List<WorkflowLeave> selectWorkflowLeaveList (WorkflowLeave workflowLeave) {
        return workflowLeaveMapper.selectWorkflowLeaveListByWorkflowLeaveAndDeptId ( workflowLeave, SecurityUtils.getLoginUser ().getUser ().getDeptId () );
    }

    /**
     * 查询请假列表带任务状态
     * @param workflowLeave 请假
     * @return 请假
     */
    @Override
    public List<WorkflowLeave> selectWorkflowLeaveAndTaskNameList (WorkflowLeave workflowLeave) {
        List<WorkflowLeave> workflowLeaves = workflowLeaveMapper.selectWorkflowLeaveList ( workflowLeave );
        List<String> collect = workflowLeaves.parallelStream ().map ( wl -> wl.getInstanceId () ).collect ( Collectors.toList () );
        if ( collect != null && ! collect.isEmpty () ) {
            List<Task> tasks = taskService.createTaskQuery ().processInstanceIdIn ( collect ).list ();
            workflowLeaves.forEach (
                    wl -> {
                        Task task = tasks.parallelStream ().filter ( t -> t.getProcessInstanceId ().equals ( wl.getInstanceId () ) ).findAny ().orElse ( null );
                        if ( task != null ) {
                            wl.setTaskName ( task.getName () );
                        }
                    }
            );
        }
        return workflowLeaves;
    }

    /**
     * 新增请假
     * @param workflowLeave 请假
     * @return 结果
     */
//    @Override
//    public int insertWorkflowLeave (WorkflowLeave workflowLeave) {
//
//        String id = UUID.randomUUID ().toString ();
//        workflowLeave.setId ( id );
//        workflowLeave.setCreateTime ( DateUtils.getNowDate () );
//        //原始启动流程方法
////        String join = StringUtils.join ( iSysUserService.selectUserNameByPostCodeAndDeptId ( "se", SecurityUtils.getLoginUser ().getUser ().getDeptId () ), "," );
////        ProcessInstance processInstance = processRuntime.start ( ProcessPayloadBuilder
////                                                                         .start ()
////                                                                         .withProcessDefinitionKey ( "leave" )
////                                                                         .withName ( workflowLeave.getTitle () )
////                                                                         .withBusinessKey ( id )
////                                                                         .withVariable ( "deptLeader", join )
////                                                                         .build () );
//
////        ActModelEntity actModel = actModelService.getById(workflowLeave.getModelId());
////        System.out.println("actModel："+actModel);
////        List<String> list = Arrays.asList("100", "20240526510405734278762496");
////        Map<String, Object> variables = new HashMap<>();
////        variables.put("approvalRole", list);
////        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
////                .start()
////                .withProcessDefinitionId(actModel.getProcessDefId())
////                .withVariables(variables).withBusinessKey(id).build());
//
////        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder.start()
////                .withProcessDefinitionId(actModel.getProcessDefId())
////                .withName(workflowLeave.getTitle())
////                .withBusinessKey(id).build());
////        System.out.println("processInstance："+processInstance);
//
//
//        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser().getUser().getUserId());
//        ActModelEntity actModel = actModelService.getById(workflowLeave.getModelId());
//        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder.start()
//                .withProcessDefinitionId(actModel.getProcessDefId()).withBusinessKey(id).withName(workflowLeave.getTitle()).build());
//        workflowLeave.setInstanceId ( processInstance.getId () );
//        workflowLeave.setState ( "0" );
//        workflowLeave.setCreateName ( SecurityUtils.getNickName () );
//        workflowLeave.setCreateBy ( SecurityUtils.getUsername () );
//        workflowLeave.setCreateTime ( DateUtils.getNowDate () );
//        return workflowLeaveMapper.insertWorkflowLeave ( workflowLeave );
//    }

    /**
     * 修改请假
     * @param workflowLeave 请假
     * @return 结果
     */
    @Override
    public int updateWorkflowLeave (WorkflowLeave workflowLeave) {
        workflowLeave.setUpdateTime ( DateUtils.getNowDate () );
        return workflowLeaveMapper.updateWorkflowLeave ( workflowLeave );
    }

    /**
     * 批量删除请假
     * @param ids 需要删除的请假ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowLeaveByIds (String[] ids) {
        return workflowLeaveMapper.deleteWorkflowLeaveByIds ( ids );
    }

    /**
     * 删除请假信息
     * @param id 请假ID
     * @return 结果
     */
    @Override
    public int deleteWorkflowLeaveById (String id) {
        return workflowLeaveMapper.deleteWorkflowLeaveById ( id );
    }

    @Override
    public WorkflowLeave selectWorkflowLeaveByInstanceId (String instanceId) {

        return workflowLeaveMapper.selectWorkflowLeaveByInstanceId ( instanceId );
    }
}
